var express = require('express');
var router = express.Router();
const fn = require('../src/fn'); 
const config = require('../src/config');
const {addLog} = require('../src/utils');

/* GET home page. */
router.post('/',async function(req, res, next) { 
  const {projectName,type,projectPath} = req.body;
  if(type == 'Ios') return res.send({code:400,msg:'暂时只支持Android'});
  if(global.building && global.building.length &&  global.building.find(item=>item.projectName == projectName)) return res.send({code:400,msg:'项目正在构建中'});
  global.building.push({projectName,type})
  // 修改data 里面的build type
  const data = fn.getData(projectName);
  data.build[type] = true;
  fn.setData(projectName,data);
  res.send({code:666,msg:'开始构建项目:'+projectName,data:req.body});
  addLog("开始构建项目......",projectName)
  let bool = false
  try{
    // 初始化项目
    if(!projectPath){
      bool = await fn.initProject(req.body,data); //拉项目是阻塞的
    }else{
      bool = true
    }
    if(!bool) return
    addLog("生成app文件......",projectName)
    try{
      // 打包出本地文件
      bool = await fn.buildPlus(req.body,data);
      if(!bool) return
      addLog("app文件生成成功进入打包队列排队......",projectName)
      if(type == 'wgt'){
        fn.buildWgt(req.body)
        return
      }
      fn.buildApp(req.body);
    }catch(err){
      addLog("项目生成app失败......",projectName)
      global.building = global.building.filter(item=>item.projectName != projectName);

    }
  }catch(err){
    addLog("项目初始化失败......",projectName)
    global.building = global.building.filter(item=>item.projectName != projectName);
  }

});

router.get('/getStatus',function(req, res, next) { 
  const {projectName} = req.query;
  const data = fn.getBuildStatus(projectName);
  res.send({code:200,msg:'获取成功',data:data});
});


module.exports = router;
